import { reactive, toRefs, computed } from "vue"
import { onShow, onReady, onUnload, onLoad } from "@dcloudio/uni-app";
import { LoginStore } from "@/store/modules/login";
import config from "@/config/config";
const uniIdCo = uniCloud.importObject("uni-id-co", { customUI: true })
const apiLogin = uniCloud.importObject('qc-login', { customUI: true });
const apiUser = uniCloud.importObject('qc-user', { customUI: true });
const systemApi = uniCloud.importObject('admin-system', { customUI: true })
const marketingApi = uniCloud.importObject('qc-marketing', { customUI: true })
import img0 from "../static/login/0.jpg"
import img1 from "../static/login/1.jpg"
import img2 from "../static/login/2.jpg"
import img3 from "../static/login/3.jpg"
/**
 * @description  手机号+密码注册
 * @param formRefs 表单校验实例
 * @param rules 表单校验规则
 * @param 
 * */
export const useSmsRegister = (formRefs, rules, agreementsRef, captchaRef) => {
	const state = reactive({
		formData: {
			password: '', //密码
			mobile: '', //手机号
			inviteCode: '', //邀请码
			code: '', //短信验证码
			captcha: '', // 图形验证码
			wxcode: '', //微信H5注册
		},
		formItem: {
			loading: false, //防抖
			eyeShow: false, //密码显示状态
			disabled: false, //禁用状态
			needCaptcha: false, // 验证码显示状态
			inviteCodeDisabled: false //邀请码的状态
		},
		uniIdRedirectUrl: '', //注册前所在的页面地址
		// 校验规则
		rules,
		// 图片验证url
		url: '',
		inviteUrl: 'https://qddh.shoutuiquan.com', //邀请链接
		// pictureVerify: ['../../static/login/0.png', '../../static/login/1.png', '../../static/login/2.png', '../../static/login/3.png', '../../static/login/4.png'],
		pictureVerify: [img0, img1, img2, img3]
	});
	onLoad(async (e) => {
		uni.$on('popupClose', (val) => {
			state.formItem.loading = false
			state.formItem.disabled = false
		})
		// #ifdef H5
		if (e.code) {
			state.formData.inviteCode = e.code
			state.formItem.inviteCodeDisabled = true
		}
		// #endif

		if (e.uniIdRedirectUrl) {
			state.uniIdRedirectUrl = decodeURIComponent(e.uniIdRedirectUrl)
		}
		// #ifdef MP-WEIXIN
		if (getCurrentPages().length === 1) {
			uni.hideHomeButton()
			console.log('已隐藏：返回首页按钮');
		}
		// #endif


		await init()

	})
	onReady(() => {
		// 兼容小程序的校验 (uview中使用)
		if (formRefs.value.setRules) formRefs.value.setRules(state.rules)
	});
	// 初始化图形验证
	const init = async () => {
		const res = await systemApi.getConfiguration()

		function generateRandomInteger(min, max) {
			return Math.floor(Math.random() * (max - min + 1)) + min;
		}
		state.inviteUrl = res?.data?.spreadUrl
		// // #ifdef APP
		// state.url = res.data.pictureVerify[generateRandomInteger(0, 4)]
		// // #endif
		// // #ifdef H5
		// state.url = state.pictureVerify[generateRandomInteger(0, 4)]
		// // #endif
		state.url = state.pictureVerify[generateRandomInteger(0, 3)]

	}
	// 兼容H5
	onShow(() => {
		// #ifdef H5
		document.onkeydown = event => {
			var e = event || window.event;
			if (e && e.keyCode == 13) { //回车键的键值为13
				submit()
			}
		};
		// #endif
	})

	// 卸载键盘事件
	onUnload(() => {
		// #ifdef H5
		document.onkeydown = false
		// #endif
	});

	/***
	 * @description: 点击获取短信验证码
	 * @param {*}
	 * @return {*}
	 * @author: white_queen
	 */

	const toSmsPage = async () => {
		try {
			const isPhone = computed(() => /^1\d{10}$/.test(state.formData.mobile))
			if (!isPhone.value) {
				return uni.showToast({
					title: "手机号码格式不正确",
					icon: 'none',
					duration: 3000
				});
			}
			const cid = uni.getStorageSync('getui_cid');
			// 查询一下该手机号有没有被注册，已经注册的账号就不让注册了
			let res = await apiLogin.getMobile({ mobile: state.formData.mobile, cid })
			if (!res.data) {
				return uni.showToast({
					title: res.errMsg,
					icon: 'none',
					duration: 3000
				});
			}
			// 发送短信
			return await apiLogin.sendSmsCode({ mobile: state.formData.mobile })
		} catch (e) {
			console.log(e.message, 111);
		}
	}


	/**
	 * @description: 注册事件
	 * @param {*} formRef 表单实例
	 * @param {*} agreementsRef 隐私协议实例
	 */
	const submit = async () => {
		formRefs.value.validator(state.formData, state.rules).then(res => {
			if (!res.isPassed) return
			// 有弹图形验证码的时候不显示按钮的loading状态
			if (state.formData.captcha !== '') {
				state.formItem.loading = true
				state.formItem.disabled = true
			}
			// #ifdef APP
			// 校验用户协议是否勾选，如果没有把提交事件传递过去，用于候选后自动注册
			if (agreementsRef.value.needAgreements.value && !agreementsRef.value.isAgree) {
				return agreementsRef.value.popup(() => submitForm())
			}
			// #endif
			// 如果校验通过直接提交注册
			submitForm()
		})
	}

	/**
	 * @description: 注册接口
	 * @param {*} 
	 */
	const submitForm = async () => {
		uni.showLoading({
			title: '加载中',
			mask: true
		});
		try {

			// 短信登录接口
			uniIdCo.loginBySms({
				mobile: state.formData.mobile,
				code: state.formData.code,
				inviteCode: state.formData.inviteCode,
				captcha: state.formData.captcha
			}).then(async (e) => {
				if (e.errCode == 0 && e.passwordConfirmed == false) {
					await setPwd()
					e.passwordConfirmed = true
				}
				const cid = uni.getStorageSync('getui_cid');
				let pushClientId = ''
				if (cid) {
					pushClientId = cid
				} else {
					uni.getPushClientId({
						success: async function(e) {
							pushClientId = e.cid
						},
						fail(e) {
							console.log(e)
						}
					})
				}
				// 初始化用户账户余额
				await apiUser.initUser({ user_id: e.uid, nickname: state.formData.mobile, register_device: pushClientId })
				// #ifdef H5
				uni.navigateTo({
					url: '/pages/user/uploadPage/uploadPage'
				})
				// #endif

				await marketingApi.setinviteUser({ my_invite_code: state.formData.inviteCode })
				// #ifdef APP
				const LoginState = LoginStore()
				LoginState.loginSuccess({ ...e, toastText: '注册成功', uniIdRedirectUrl: state.uniIdRedirectUrl })
				// #endif
				uni.hideLoading()
				state.formItem.loading = false
				state.formItem.disabled = false
			}).catch(async e => {
				console.log({ ...e }, '我是短信登录的验证码');
				uni.hideLoading()
				state.formItem.loading = false
				state.formItem.disabled = false
				// 输入错误次数超过3次 提示图形验证码
				if (e.errCode == 'uni-id-captcha-required') {
					state.formData.captcha = ""
					state.formItem.needCaptcha = true
				}
				// 图形验证码输入错误
				if (e.errCode == "uni-captcha-verify-fail") {
					uni.showToast({
						title: e.errMsg,
						icon: 'none',
						duration: 3000
					});
					state.formData.captcha = ""
					state.formItem.needCaptcha = true
					// 重新刷新验证码
					captchaRef.value.getImageCaptcha()
				}
				if (e.errCode == 'uni-id-mobile-verify-code-error') {
					uni.showToast({
						title: e.errMsg,
						icon: 'none',
						duration: 3000
					});
					state.formItem.needCaptcha = false
				}
			})
		} catch (e) {
			console.log(e);
		}
	}

	// 设置密码
	const setPwd = async () => {
		try {
			// 重置短信验证码状态
			await apiLogin.setSmsCode({ code: state.formData.code })
			// 重置图形验证码
			await apiLogin.setSmsCode({ code: state.formData.captcha })
			// 设置密码
			await uniIdCo.setPwd({ code: state.formData.code, password: state.formData.password, captcha: state.formData.captcha })
		} catch (e) {
			console.log({ ...e }, '我是设置密码的验证码');
		}
	}

	// 跳转下载页
	const download = () => {
		uni.navigateTo({
			url: '/pages/user/uploadPage/uploadPage'
		})
	}

	// 去登录
	const toLoing = () => {
		uni.navigateBack()
	}

	// 关闭验证码弹出层
	const close = () => {
		state.formItem.needCaptcha = false
	}

	return {
		...toRefs(state),
		submit,
		toLoing,
		toSmsPage,
		download,
		close
	};
};